package com.eroly.controller;

import com.eroly.common.GlobalSt;
import com.eroly.util.ImageCodeUtil;
import com.eroly.util.OperaServletUtil;
import com.eroly.util.StringUtil;
import com.eroly.util.VerifyCodeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/ImgCode")
public class ImageCodeController{
    Logger logger = LoggerFactory.getLogger(Logger.class);
    @Autowired
    OperaServletUtil operaServlet;

    /**
     * 校验图形验证码
     * @param iptCode
     * @return
     */
    @RequestMapping("/checkImgCode")
    @ResponseBody
    public Map<String,Object> checkImgCode(String iptCode){
        logger.info("发送的报文：{}",iptCode);
        Map<String,Object> result = new HashMap<String,Object>();
        String status = StringUtil.isEmpty(iptCode)?GlobalSt.SYSTEM_STATU_ZERO:
                (iptCode.equalsIgnoreCase((String) operaServlet.getSessValue(GlobalSt.LOGIN_IMG_CODE))?GlobalSt.SYSTEM_STATU_ONE:
                        GlobalSt.SYSTEM_STATU_ZERO);
        operaServlet.removeSessValue(GlobalSt.LOGIN_IMG_CODE);
        result.put(GlobalSt.SYSTEM_STATUS, status);
        return result;
    }
    //将图片以IO流的形式输出到response里 ImageCodeUtil
    @RequestMapping("/getImageCode.do")
    public void getImageCode(HttpServletResponse response, HttpSession session){
        logger.info("getImageCode.do，生成图形验证码");
        Object[] objects = ImageCodeUtil.createImage();
        String code = (String) objects[0];

        BufferedImage image = (BufferedImage) objects[1];
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        OutputStream os = null;
        response.setHeader("Pragma","no-cache");
        response.setHeader("Cache-Control","no-cache");
        response.setDateHeader("Expires",0);
        response.setContentType("image/png");
        try {
            os = response.getOutputStream();
            ImageIO.write(image, "png", os);
            os.flush();
            operaServlet.setSessValue(GlobalSt.LOGIN_IMG_CODE,code);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //将图片以IO流的形式输出到response里 VerifyCodeUtils
    @RequestMapping("/getImageCode2.do")
    public void getImageCode2(HttpServletResponse response, HttpSession session){
        logger.info("getImageCode2，生成图形验证码");
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        int w = 80, h = 30;
        BufferedImage bufferedImage = null;
        OutputStream os = null;
        try {
            bufferedImage = VerifyCodeUtils.outputImage(w, h, verifyCode);
            response.setHeader("Pragma","no-cache");
            response.setHeader("Cache-Control","no-cache");
            response.setDateHeader("Expires",0);
            response.setContentType("image/png");
            String base64 = "";
            // 将内存中的图片通过流动形式输出到客户端
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage,"",baos);
            byte[] bytes = baos.toByteArray();

            base64 =  new BASE64Encoder().encodeBuffer(bytes).trim();
            os = response.getOutputStream();
            ImageIO.write(bufferedImage,    "png", os);
            os.flush();
            session.setAttribute(GlobalSt.LOGIN_IMG_CODE,verifyCode);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //base64方式返回 VerifyCodeUtils
    @RequestMapping(value = "/getImageCodeBase64")
    @ResponseBody
    public String getImageCode3(HttpSession session){
        logger.info("getImageCodeBase64，生成图形验证码");
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        int w = 80, h = 30;
        BufferedImage bufferedImage;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();;
        String base64 = "";
        try {
            bufferedImage = VerifyCodeUtils.outputImage(w, h, verifyCode);
            // 将内存中的图片通过流动形式输出到客户端
            ImageIO.write(bufferedImage,"png",baos);
            byte[] bytes = baos.toByteArray();

            base64 =  new BASE64Encoder().encodeBuffer(bytes).trim();
            session.setAttribute(GlobalSt.LOGIN_IMG_CODE,verifyCode);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(baos!=null){
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return base64;
    }
}
